package com.bolt.core.view.tag;

import com.bolt.common.utils.SpringContextUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.core.view.components.*;
import com.bolt.core.view.config.UIProperties;

import javax.servlet.jsp.JspException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/3/3.
 */
public class QueryFormTag extends AbstractClosingTag {

    private String action;

    private String path;

    private String dataGrid;

    @Override
    public ComponentsBase getUI() {
        if (getPageRepository().exists(path, id)) {
            PageView pageView = getPageRepository().findPage(path);
            Form form = pageView.getForm(id);
            if(StrUtil.isEmpty(action)){
                setAction(form.getQueryAction());
            }
            return extractQueryForm(form);

        } else {
            throw new ServiceException("pageView:['" + path + "'],form:['" + id + "'] not found");
        }

    }

    private QueryForm extractQueryForm(Form form) {
        QueryForm queryForm = new QueryForm();
        queryForm.setAction(StrUtil.isEmpty(this.action) ? form.getQueryAction() : this.action);
        queryForm.setDataGrid(dataGrid);
        UIProperties uiProperties = getUiProperties();
        form.setTheme(uiProperties.getTheme());
        form.setTemplateDir(uiProperties.getDefaultPath());
        form.setTemplateEngine(getFreemarkerTemplateEngine());
        List <FormItem> newGroups = new ArrayList <>();
        for (List <FormItem> group : form.getGroup()) {
            newGroups.addAll(group);
        }
        newGroups.addAll(form.getHiddenFormItems());
        for (FormItem formItem : newGroups) {
                evaluateParams(queryForm,formItem);
                queryForm.addFormItems(formItem);
        }
        return queryForm;
    }


    private void evaluateParams(QueryForm queryForm,FormItem item) {
        if (!item.existParameter("placeholder")) {
            item.addDynamicParameters("placeholder", item.getLabel());
        }
        if(item.isQueryField() && StrUtil.isNotBlank(item.getMatchType())){
            FormItem hiddenText = new FormItem();
            hiddenText.setType("hidden");
            hiddenText.setId("filters");
            hiddenText.addParameter("value",item.getName()+":"+newName(item.getName(),item.getMatchType()));
            SpringContextUtil.inject(hiddenText);
            queryForm.addFormItems(hiddenText);
        }
    }

    @Override
    public void populateParams() {
        super.populateParams();
        QueryForm form = (QueryForm) component;
        List <FormItem> group = form.getGroup();
        group.forEach(k -> {
            k.setTemplateDir(form.getTemplateDir());
            k.setTheme(form.getTheme());
            k.setTemplateEngine(form.getTemplateEngine());
        });
    }

    private String newName(String name, String matchType) {
        if (StrUtil.isEmpty(matchType)) {
            return name;
        }
        StringBuffer newName = new StringBuffer("search[");

        if (StrUtil.indexOf(matchType, '_') > 0) {
            newName.append("'" + matchType + "'");
        } else {
            newName.append("'" + matchType.toUpperCase() + "_" + name + "'");
        }
        newName.append("]");
        return newName.toString();
    }



    @Override
    public int doEndTag() throws JspException {
        QueryForm queryForm = (QueryForm) component;
        for (FormItem item : queryForm.getGroup()) {
            if("hidden".equals(item.getType() )){
                item.end(getRequest(), getResponse(), pageContext.getOut());
            }else{
                Decorate decorate = Decorate.buildQueryFormColumnDecorate(item);
                decorate.start(getRequest(), getResponse(), pageContext.getOut());
                decorate.end(getRequest(), getResponse(), pageContext.getOut());
            }

        }
        queryForm.end(getRequest(), getResponse(), pageContext.getOut());
        queryForm.getGroup().clear();
        return EVAL_PAGE;
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getDataGrid() {
        return dataGrid;
    }

    public void setDataGrid(String dataGrid) {
        this.dataGrid = dataGrid;
    }

}
